package com.ruoyi.wapp.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.base.BaseEntity;
import com.ruoyi.common.constant.CacheKeyConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.ResultConstants;
import com.ruoyi.common.utils.Md5Utils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.WdyConsume;
import com.ruoyi.system.domain.WdyUser;
import com.ruoyi.system.dto.RechargeCallback;
import com.ruoyi.system.service.*;
import com.ruoyi.wapp.controller.base.BaseController;
import com.ruoyi.wapp.controller.base.Result;
import com.ruoyi.wapp.util.MyConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 *
 */
@Controller
public class CommonController extends BaseController {

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private IWdyRechargeService wdyRechargeService;

    @Autowired
    private IWdyWithdrawService wdyWithdrawService;

    @Autowired
    private IWdyUserService wdyUserService;

    @Autowired
    private IWdyConsumeService wdyConsumeService;
    @GetMapping("/getDictDataByType")
    @ResponseBody
    public Result getDictDataByType(String type) {
        return Result.ok().put("list", sysDictDataService.selectDictDataByType(type));
    }

    @GetMapping("/getConfig")
    @ResponseBody
    public Result getConfig() {
        Result result = Result.ok();
        result.put("vcRatio",redisTemplate.opsForHash().get(CacheKeyConstants.SYS_CONFIG_MAP, CacheKeyConstants.VC_RATIO));
        BigDecimal usdtCny;
        if(!redisTemplate.opsForHash().hasKey(CacheKeyConstants.EXCHANGE_RATE, Constants.USDT_CNY)) {
            usdtCny = new BigDecimal(redisTemplate.opsForHash().get(CacheKeyConstants.SYS_CONFIG_MAP, Constants.USDT_CNY).toString());
        } else {
            usdtCny = (BigDecimal) redisTemplate.opsForHash().get(CacheKeyConstants.EXCHANGE_RATE, Constants.USDT_CNY);
        }
        result.put("usdtCny", usdtCny);
        return result;
    }

    @PostMapping(value = "/rechargeCallback")
    @ResponseBody
    public String rechargeCallback(RechargeCallback callback) {
        try {
            log.info("支付回调:{}", JSON.toJSONString(callback));
            wdyRechargeService.rechargeCallback(callback);
            return "success";
        } catch (Exception e) {
            log.error("支付回调异常", e);
            return "";
        }
    }

    @PostMapping("/service")
    public Result service(String serviceName, String reqData, String sign) {
        if(StringUtils.isEmpty(serviceName)) {
            return Result.error(ResultConstants.FI1000, "serviceName" + MessageUtils.message("not.null"));
        }
        if(StringUtils.isEmpty(reqData)) {
            return Result.error(ResultConstants.FI1000, "reqData" + MessageUtils.message("not.null"));
        }
        if(StringUtils.isEmpty(sign)) {
            return Result.error(ResultConstants.FI1000, "sign" + MessageUtils.message("not.null"));
        }
        if(!Md5Utils.hash(reqData + Constants.WALLET_SIGN_KEY).equalsIgnoreCase(sign)) {
            return Result.error(ResultConstants.FI1000, "sign无效");
        }

        JSONObject json = JSON.parseObject(reqData);
        String userId = json.getString("userId");
        if(StringUtils.isEmpty(userId)) {
            return Result.error(ResultConstants.FI1000, "userId" + MessageUtils.message("not.null"));
        }
        if("getUser".equals(serviceName)) {
            QueryWrapper<WdyUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("vc_amount", "vc_consume_amount", "vc_withdraw_amount");
            queryWrapper.eq("user_id", userId);
            WdyUser user = wdyUserService.getOne(queryWrapper);
            if(user == null) {
                return Result.error(ResultConstants.FI1000, "userId" + MessageUtils.message("param.error"));
            }
            return Result.ok().put("user", JSON.toJSON(JSON.toJSON(user).toString()));
        } else if("consume".equals(serviceName)) {
            WdyConsume wdyConsume = new WdyConsume();
            wdyConsume.setUserId(userId);
            wdyConsume.setConsumeId(json.getString("consumeId"));
            wdyConsume.setVcAmount(json.getBigDecimal("vcAmount"));
            wdyConsume.setVcConsumeAmount(json.getBigDecimal("vcConsumeAmount"));
            wdyConsume.setVcWithdrawAmount(json.getBigDecimal("vcWithdrawAmount"));
            wdyConsume.setRemark(json.getString("remark"));
            wdyConsumeService.consume(wdyConsume);
        } else if("loginWallet".equals(serviceName)) {
            QueryWrapper<WdyUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("del_flag", BaseEntity.NOT_DELETED);
            WdyUser user = wdyUserService.getOne(queryWrapper);
            if(user == null) {
                return Result.error(ResultConstants.FI1000, "userId" + MessageUtils.message("param.error"));
            }
            String token = UUID.randomUUID().toString().replace("-", "");
            String tokenCacheKey = CacheKeyConstants.getTempletString(CacheKeyConstants.TOKEN_TPL, token);
            redisTemplate.opsForValue().set(tokenCacheKey, user, MyConstants.CONFIG.SESSION_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok().put("token", token);
        } else {
            return Result.error(ResultConstants.FI1000, "serviceName无效");
        }
        return Result.ok();
    }
}
